import { ref } from 'vue'

export default function useHistoricalSearch() {
  // 数据
  const searchList = ref<Array<string>>(
    localStorage.getItem('searchList') ? JSON.parse(localStorage.getItem('searchList')!) : [],
  )
  const show = ref(false)

  // 添加
  function add(val: string) {
    // 判断是否已经存在
    if (searchList.value.includes(val)) {
      // 将其置顶
      searchList.value = searchList.value.filter((item) => item !== val)
    }
    searchList.value.unshift(val)
    localStorage.setItem('searchList', JSON.stringify(searchList.value))
  }

  // 返回模糊搜索结果
  function fuzzySearch(val: string) {
    const ex = new RegExp(val, 'i')
    const list = searchList.value
      .filter((item) => item != val)
      .filter((item) => ex.test(item))
      .slice(0, 5)

    return list
  }

  // 移除
  function remove(val: string) {
    searchList.value = searchList.value.filter((item) => item !== val)
    localStorage.setItem('searchList', JSON.stringify(searchList.value))
  }

  return { searchList, show, add, fuzzySearch, remove }
}
